package com.hh.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hh.common.ErrorCode;
import com.hh.constant.RedisLuaScriptConstant;
import com.hh.entity.domain.Thumb;
import com.hh.entity.domain.User;
import com.hh.entity.dto.thumb.DoThumbRequest;
import com.hh.entity.enums.LuaStatusEnum;
import com.hh.exception.BusinessException;
import com.hh.mapper.ThumbMapper;
import com.hh.service.ThumbService;
import com.hh.service.UserBehaviorService;
import com.hh.service.UserService;
import com.hh.utils.RedisKeyUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * com.hh.service.impl
 *
 * @author hanhui
 * @version 1.0
 * @date 2025/7/31 14:01
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ThumbServiceImpl extends ServiceImpl<ThumbMapper, Thumb>
        implements ThumbService {

    private final UserService userService;
    private final UserBehaviorService userBehaviorService;

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public Boolean doThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        return executeThumbOperation(doThumbRequest, request, RedisLuaScriptConstant.THUMB_SCRIPT);
    }

    @Override
    public Boolean unThumb(DoThumbRequest doThumbRequest, HttpServletRequest request) {
        return executeThumbOperation(doThumbRequest, request, RedisLuaScriptConstant.UNTHUMB_SCRIPT);
    }


    private Boolean executeThumbOperation(DoThumbRequest doThumbRequest, HttpServletRequest request, RedisScript<Long> luaScript) {
        // 检查请求参数是否为空
        if (doThumbRequest == null || doThumbRequest.getPostId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_NULL);
        }
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        Long postId = doThumbRequest.getPostId();
        String timeSlice = getTimeSlice();
        String tempThumbKey = RedisKeyUtil.getTempThumbKey(timeSlice);
        String userThumbKey = RedisKeyUtil.getUserThumbKey(loginUser.getId());
        // 执行Lua脚本
        Long result = redisTemplate.execute(
                luaScript,
                Arrays.asList(tempThumbKey, userThumbKey),
                loginUser.getId(),
                postId
        );
        if (LuaStatusEnum.FAIL.getValue().equals(result)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return LuaStatusEnum.SUCCESS.getValue().equals(result);
    }

    // 获取时间片
    private String getTimeSlice() {
        // 获取当前时间
        DateTime dateTime = DateUtil.date();
        // 获取当前时间前最近的整数秒
        return DateUtil.format(dateTime, "HH:mm") +":"+ (DateUtil.second(dateTime) / 10) * 10;
    }

    @Override
    public Boolean hasThumb(Long blogId, Long userId) {
        return redisTemplate.opsForHash().hasKey(
                RedisKeyUtil.getUserThumbKey(userId),
                blogId.toString());
    }
}
